//
//  WBOriginalView.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/21.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit
import SnapKit
class WBOriginalView: UIView {
    
    // MARK: -  当前view的底部约束
    var originalViewBottomConstraint: Constraint?

    // MARK: -  模型属性
    var status: WBStatusModel? {
        
        didSet {
            
            headImageView.sd_setImageWithURL(NSURL(string: (status?.user?.profile_image_url)!), placeholderImage: UIImage(named: "avatar_default"))
            
            nameLabel.text = status?.user?.screen_name
            
            memberRankImageView.image = setMemberRankImage((status?.user?.mbrank)!)
            
            timeLabel.text = getWeiBoTimeString((status?.created_at)!)
            placeLabel.attributedText = getSourceString(status?.source)
            
            verifiedImageView.image = setVerifiedImage((status?.user?.verified)!)
            
            //处理图文混排问题
            mainTextLabel.attributedText = getWeiBoAttributeText((status?.text)!)
            
            self.originalViewBottomConstraint?.uninstall()
            if status?.pic_urls?.count != 0 {
                
                pictureCollectionView.pictures = status?.pic_urls
                self.snp_makeConstraints(closure: { (make) -> Void in
                    
                    self.originalViewBottomConstraint = make.bottom.equalTo(pictureCollectionView.snp_bottom).offset(10).constraint
                })
                pictureCollectionView.hidden = false
                
            }else {
                
                self.snp_makeConstraints(closure: { (make) -> Void in
                    
                    self.originalViewBottomConstraint = make.bottom.equalTo(mainTextLabel.snp_bottom).offset(10).constraint
                })
                pictureCollectionView.hidden = true
            }
        }
    }
    
    
    // MARK: -  处理图文混排问题
    func getWeiBoAttributeText(text: String) -> NSMutableAttributedString? {
        
        
        //把微博正文的字符串转换成一个可变的附文本
        let previousAttr = NSMutableAttributedString(string: text)
        
        //定义一个数组保存遍历到的模型
        var matchArray: [WBMatchResultModel] = [WBMatchResultModel]()

        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, result, range, _) -> Void in
            
//            print(result.memory)

            let matchModel  = WBMatchResultModel(string: (result.memory as! String), range: range.memory)
            matchArray.append(matchModel)
        }
        
        for matchModel in matchArray.reverse() {
            
            guard let emoticonModel = WBEmoticonTool.sharedTools.getEmoticonWithChs(matchModel.string) else {
                
                return NSMutableAttributedString(string: "")
            }
            
            
            let path = "\(emoticonModel.path!)\(emoticonModel.png!)"
            let image = UIImage(named: path, inBundle: WBEmoticonTool.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            //得到行高
            let lineHeight = UIFont.systemFontOfSize(14).lineHeight
            
            
            //创建文本附件
            let att = NSTextAttachment()
            att.image = image
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            //创建一个不可变附文本
            let attr = NSAttributedString(attachment: att)
            
            previousAttr.replaceCharactersInRange(matchModel.range, withAttributedString: attr)

        }
        
        return previousAttr
    }
    
    // MARK: -  获取微博发布时间的方法
    func getWeiBoTimeString(createdTime: String) -> String {
        
        //创建微博格式化器
        let formatter = NSDateFormatter()
        //设置格式   Fri Apr 22 17:15:54 +0800 2016
        formatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        //设置locale
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        
        //获取微博date
        let weiboDate = formatter.dateFromString(createdTime)!
        let isThisYear = weiBoTimeIsThisYear(weiboDate)
        
        if isThisYear {
            /*
            - 如果是今天
                - 如果 < 60 s  显示格式: 刚刚
            - 如果 >=60 && < 60 * 60  显示格式: xx分钟前
            - 其他 显示格式: xx小时前
            - 如果是昨天
            -例如 2016-04-22 19:19:19  显示格式: 昨天 19:19
            - 其他
            -例如 2016-04-04 20:20:20  显示格式: 04月04日 20:20
            */
            // 日历类
            let calendar =  NSCalendar.currentCalendar()
            if calendar.isDateInToday(weiboDate) {
                
                // 计算当前的日期 和微博日期的差值
                let s = NSDate().timeIntervalSinceDate(weiboDate)
                if s < 60 {
                    return "刚刚"
                }else if s >= 60 && s < 60*60 {
                    
                    return "\(Int(s/60))分钟前"
                }else {
                    
                    return "\(Int(s/3600))小时前"
                }
                
            }else if calendar.isDateInYesterday(weiboDate) {
                
                formatter.dateFormat = "昨天 HH:mm"
                return formatter.stringFromDate(weiboDate)
                
            }else {
                
                formatter.dateFormat = "MM月dd日 HH:mm"
                return formatter.stringFromDate(weiboDate)
            }
            
        }else {
            /*
            - 如果不是今年
            -例如: 2015-01-01 18:18:18 显示格式: 2015年01月01日 18:18
            */
            formatter.dateFormat = "yyyy年MM月dd日 HH:mm"
            return formatter.stringFromDate(weiboDate)
        }

    }
    
    // MARK: -  判断是否是今年
    func weiBoTimeIsThisYear(weibodate: NSDate) -> Bool {
        
        //创建微博格式化器
        let formatter = NSDateFormatter()
        //设置格式   Fri Apr 22 17:15:54 +0800 2016
        formatter.dateFormat = "yyyy"
        //设置locale
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        
        //得到微博时间的字符串
        let weiBoDateString = formatter.stringFromDate(weibodate)
        //获取当前时间的字符串
        let currentDateString = formatter.stringFromDate(NSDate())
        
        if weiBoDateString == currentDateString {
            return true
        }else {
            return false
        }
        
    }
    
    // MARK: -  处理微博来源字符串
    private func getSourceString(source: String?) -> NSMutableAttributedString {
        
        guard var sourceString = source where sourceString.containsString("\">") else {
            
            return NSMutableAttributedString(string: "")
        }

        let startRange = sourceString.rangeOfString("\">")!
        let endRange = sourceString.rangeOfString("</a")!
        
        sourceString = sourceString.substringWithRange(startRange.endIndex..<endRange.startIndex)
        sourceString = "来自 \(sourceString)"
        
        let result = NSMutableAttributedString(string: sourceString)
        let range = (sourceString as NSString).rangeOfString("来自")
        
        result.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: range)
        
        return result
        
    }
    
    // MARK: -  设置微博认证图标
    private func setVerifiedImage(verifiedNum: Int) -> UIImage? {
        
        switch verifiedNum {
        case 0:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return nil
        }

    }
    
    // MARK: -  设置会员等级图标
    private func setMemberRankImage(memberRank: Int) -> UIImage? {
        
        if memberRank > 0 && memberRank < 7 {
            return UIImage(named: "common_icon_membership_level\(memberRank)")
        }else {
            return UIImage(named:"common_icon_membership_expired")
        }
    }
 
    // MARK: -  重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    // MARK: -  重写init方法时必须实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  设置视图
    private func setUpUI() {
        
        self.backgroundColor = UIColor.whiteColor()

        addSubview(headImageView)
        addSubview(nameLabel)
        addSubview(memberRankImageView)
        addSubview(timeLabel)
        addSubview(placeLabel)
        addSubview(verifiedImageView)
        addSubview(mainTextLabel)
        addSubview(pictureCollectionView)
        
        
        headImageView.snp_makeConstraints { (make) -> Void in
            make.leading.top.equalTo(10)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(headImageView.snp_trailing).offset(10)
            make.top.equalTo(headImageView)
        }
        
        memberRankImageView.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(nameLabel.snp_trailing).offset(10)
            make.centerY.equalTo(nameLabel)
        }
        
        timeLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(nameLabel)
            make.bottom.equalTo(headImageView)
        }
        
        placeLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
            make.bottom.equalTo(timeLabel)
        }
        
        verifiedImageView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(headImageView.snp_trailing).offset(0)
            make.centerY.equalTo(headImageView.snp_bottom).offset(0)
        }
        
        mainTextLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(10)
            make.top.equalTo(headImageView.snp_bottom).offset(10)
            make.width.equalTo(kScreenW-20)
        }
        
        pictureCollectionView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(mainTextLabel.snp_bottom).offset(10)
            make.leading.equalTo(mainTextLabel)
        }
        
        self.snp_makeConstraints { (make) -> Void in
            
            self.originalViewBottomConstraint = make.bottom.equalTo(pictureCollectionView).offset(10).constraint
        }

    }
    

    
    // MARK: -  懒加载控件
    // MARK: -  头像
    private lazy var headImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_default"))
    
    // MARK: -  昵称
    private lazy var nameLabel: UILabel = UILabel(textColor: UIColor.darkGrayColor(), textFont: 14)
    
    // MARK: -  会员等级
    private lazy var memberRankImageView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    
    // MARK: -  时间
    private lazy var timeLabel: UILabel = UILabel(textColor: themeColor, textFont: 10)
    
    // MARK: -  地点
    private lazy var placeLabel: UILabel = UILabel(textColor: themeColor, textFont: 10)
    
    // MARK: -  认证
    private lazy var verifiedImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_enterprise_vip"))

    // MARK: -  正文
    private lazy var mainTextLabel: UILabel = {
        
        let mainTextLabel = UILabel(textColor: UIColor.blackColor(), textFont: 14)
        mainTextLabel.numberOfLines = 0
        return mainTextLabel
    }()
    
    // MARK: -  图片
    private lazy var pictureCollectionView: WBPictureCollectionView = WBPictureCollectionView()
    
}
